<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>
    <!--
      @selection-change：多选按钮改变以后的处理函数
    -->
		<!--列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" >
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span style="color:lawngreen" v-if="scope.row.state == 1">启用</span>
          <span style="color: red" v-else-if="scope.row.state == 0">禁用</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="负责人" width="120" >
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180" >
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <!--
              scope.$index：当前列的索引
              scope.row：当前行的所有数据，就相当于把当前行的这个对象获取出来
          -->
          <el-button type="warning" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--
      :disabled="this.sels.length===0"：当这个模型层的参数长度为0时不可用
    -->
    <!--分页工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
    <!--
      :rules：表单校验规则
    -->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门编号" prop="sn">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="部门经理">
          <!--<el-input v-model="editForm.manager" auto-complete="off"></el-input>-->

          <!--elementui提供的单选下拉框
            :key：对象中的唯一标识
            :label：要在输入框中显示的值
            :value：要传到后端的值
          -->
          <el-select clearable v-model="editForm.manager" value-key="id" placeholder="请选择">
            <el-option
                v-for="employee in employees"
                :key="employee.id"
                :label="employee.username"
                :value="employee">
              <span style="float: left">{{ employee.username }}</span><!--左边显示-->
              <span style="float: right; color: #8492a6; font-size: 13px">{{ employee.phone }}</span><!--右边显示-->
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="上级部门" >
          <!--elementUI提供的级联选择器-->
          <!--
            options：绑定的级联树
          -->

            <el-cascader
                v-model="editForm.parent"
                :options="treeDepartments"
                :props="{
                checkStrictly: true,
                value: 'id',
                label: 'name'
              }" clearable></el-cascader>

        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
			  treeDepartments: [],
        employees: [],
        title: "",
				filters: {
          keyword: ''
				},
				departments: [],
				total: 0,
				currentPage: 1,
        pageSize: 5,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }//name的校验规则 blur在失去焦点时校验 required不能为空
					],
          sn: [
            { required: true, message: '请输入部门编号', trigger: 'blur' }
          ]
				},
				//编辑界面数据
				editForm: {
					id: null,
					name: '',
          sn: '',
					state: 1,//状态
					manager: null,//部门经理
          parent: null//上级部门
				}
			}
		},
		methods: {
		  /*关键字查询*/
      search(){
        this.currentPage = 1;
        this.getDepartments();
      },

			//性别显示转换
			formatState: function (row, column) {
				return row.state == 1 ? '启用' : row.state == 0 ? '弃用' : '未知';
			},

			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},

			//获取部门列表
			getDepartments() {
				let para = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.filters.keyword
				};
				//开启页面忙等
				this.listLoading = true;
				/*请求后端分页数据*/
        this.$http.post("/dept",para).
        then(res=>{//处理请求成功的回调函数
          this.listLoading = false;
          this.departments = res.data.list
          this.total = res.data.total
        }).catch(res=>{//处理请求失败的回调函数
          this.$message.error("网络异常")
        })
			},

			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.delete("/dept/"+row.id).
          then(res=>{
             if(res.data.success){//后台返回成功
               //根据业务需求，删除后一般1、刷新到首页，2、刷新到上一页，3、本页还有数据就停留在本页
               //刷新到第一页
               this.$message.success(res.data.message);
               this.search();

             }else {//后台返回失败
               this.$message.error(res.data.message);
               this.search();
             }
          }).catch(res=>{
            this.$message.error("网络异常")
          })
				}).catch(() => {

				});
			},

			//显示编辑界面
			handleEdit: function (index, row) {
        this.getTree();
        if(this.$refs['editForm']){
          this.$refs['editForm'].resetFields(); //取消表单校验提示
        }
        this.title = "编辑";
				this.editFormVisible = true;//显示编辑页面
        // console.log(row.parent)
				this.editForm = Object.assign({}, row);//对象克隆,回显数据
        if(row.parent) {//判断这条数据有无上级部门，有才回显
          let dirPathArr = row.dirPath.split("/");//获取dirPath并将其分割成字符数组
          let newDirPathArr = [];//创建一个新的数组
          for (let i = 1; i < dirPathArr.length - 1; i++) {//循环，去头去尾并转换成number类型的数组复制到新数组中
            newDirPathArr.push(parseInt(dirPathArr[i]));
          }
          this.editForm.parent = newDirPathArr;//将新数组赋值给表单的parent属性，进行回显
        }
			},

			//显示新增界面
			handleAdd: function () {
        this.getTree();
        if(this.$refs['editForm']){
          this.$refs['editForm'].resetFields(); //取消表单校验提示
        }
        this.title = "新增";
				this.editFormVisible = true;//显示编辑页面
				this.editForm = {//清空表单
          id: null,
          name: '',
          sn: '',
          state: 1,
          manager: null,
          parent: null
				};
			},

			//编辑
			editSubmit: function () {
        /*
        * this.$refs.editForm.validate((valid) 获取到指定的表单，然后主动发起校验
        * */
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;//开启忙等
							//NProgress.start();
							let para = Object.assign({}, this.editForm);//克隆表单
              let parentArr = para.parent//取出父级部门的数组
              if(parentArr){
                let parent = {id: parentArr[parentArr.length - 1]}//获取到最后上一层部门
                para.parent = parent
              }

              //处理表单数据
              /*提交表单*/
               this.$http.put("/dept",para).
               then(res=>{
                 this.editLoading = false;//关闭编辑确认按钮忙等
                 if(res.data.success){//后台返回成功
                   //根据业务需求，删除后一般1、刷新到首页，2、刷新到上一页，3、本页还有数据就停留在本页
                   //刷新到第一页
                   this.editFormVisible = false;//关闭表单弹窗
                   this.$message.success(res.data.message);
                   this.search();
                   this.$refs['editForm'].resetFields();
                 }else {//后台返回失败
                   this.$message.error(res.data.message);
                   this.search();
                 }
               }).catch(res=>{
                 this.editLoading = false;//关闭编辑确认按钮忙等
                 this.$message.error("网络异常")
               })
							/*editDepartment(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDepartments();
							});*/
						});
					}
				});
			},

      /*批量删除绑定的改变事件*/
			selsChange: function (sels) {
				this.sels = sels;
			},

			//批量删除
			batchRemove: function () {
			  /*将sels这个数组中的每个对象的id取出来装到ids数组里面*/
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.patch("/dept",ids).
          then(res=>{
            if(res.data.success){//后台返回成功
              //根据业务需求，删除后一般1、刷新到首页，2、刷新到上一页，3、本页还有数据就停留在本页
              //刷新到第一页
              this.$message.success(res.data.message);
              this.search();
            }else {//后台返回失败
              this.$message.error(res.data.message);
              this.search();
            }
          }).catch(res=>{
              this.$message.error("网络异常")
          })
				}).catch(() => {

				});
			},

      //查询所有员工
      getEmployees(){
			  this.$http.get("/emp").
        then(res=>{
          this.employees = res.data
        }).catch(res=>{
          this.$message.error("查询所有员工失败")
        })
      },

      //获取部门树
      getTree(){
			  this.$http.get("/dept/getTree").
        then(res=>{
          this.treeDepartments = res.data
        }).catch(res=>{
          this.$message.error("查询部门树失败")
        })
      }
		},
		mounted() {
			this.getDepartments();
			this.getEmployees();//为了性能考虑，在页面加载完成就获取所有员工
		}
	}

</script>

<style scoped>

</style>